<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1 th:text="#{home.page}"/>
<h1 th:text="${user.getName()}"/>

<a onclick="changeLanguage('zh_CN')">zh</a>
<a onclick="changeLanguage('en_US')">en</a>


<input id="userId" type="text" placeholder="请输入用户id"/>
<button type="button" onclick="registerUserId()" th:text="#{button.login}"></button>

<input id="toUserId" type="text" placeholder="请输入对方用户id">

<div id="chatWindow" style="width:500px; height: 500px; border: black solid 1px;"></div>
<input id="chatInput" type="text" placeholder="在此输入聊天内容" />

<script type="text/javascript">
    const chatWindow = document.getElementById("chatWindow");
    const chatInput = document.getElementById("chatInput");

    chatInput.addEventListener("keydown", function (e) {
        var theEvent = window.event || e;
        var code = theEvent.keyCode || theEvent.which || theEvent.charCode;
        if (code == 13) {

            addMessageIntoChatWindow(this.value);

            let toUserId = document.getElementById("toUserId").value;

            let sendMsg = {
                to_user_id:toUserId,
                msg: this.value
            };
            socket.send(JSON.stringify(sendMsg));

            this.value = "";
        }
    });

    function addMessageIntoChatWindow(value){
        var pTag = document.createElement("p");
        pTag.textContent = value;
        chatWindow.append(pTag);
    }

    // document.onload = openSocket();
    
    function registerUserId() {
        var userId = document.getElementById("userId").value;
        openSocket(userId);
    }

    var socket;
    function openSocket(userId) {
        if(typeof(WebSocket) == "undefined") {
            console.log("您的浏览器不支持WebSocket");
        }else{
            console.log("您的浏览器支持WebSocket");
            //实现化WebSocket对象，指定要连接的服务器地址与端口  建立连接
            //等同于socket = new WebSocket("ws://localhost:8888/xxxx/im/25");
            //var socketUrl="${request.contextPath}/im/"+$("#userId").val();

            var port = window.location.port==""?"":":"+window.location.port;

            var socketUrl="ws://"+window.location.hostname+":8082/imserver";
            console.log(socketUrl);
            if(socket!=null){
                socket.close();
                socket=null;
            }
            socket = new WebSocket(socketUrl);
            //打开事件
            socket.onopen = function() {
                console.log("websocket已打开");

                let msg = {
                    to_user_id: document.getElementById("toUserId").value,
                    msg: "客户端已连接"
                }

                socket.send(JSON.stringify(msg));
            };
            //获得消息事件
            socket.onmessage = function(msg) {
                console.log(msg.data);

                addMessageIntoChatWindow(msg.data);

                //发现消息进入    开始处理前端触发逻辑
            };
            //关闭事件
            socket.onclose = function() {
                console.log("websocket已关闭");
            };
            //发生了错误事件
            socket.onerror = function() {
                console.log("websocket发生了错误");
            }
        }
    }
    function sendMessage() {
        if(typeof(WebSocket) == "undefined") {
            console.log("您的浏览器不支持WebSocket");
        }else {
            console.log("您的浏览器支持WebSocket");
            console.log('{"toUserId":"'+$("#toUserId").val()+'","contentText":"'+$("#contentText").val()+'"}');
            socket.send('{"toUserId":"'+$("#toUserId").val()+'","contentText":"'+$("#contentText").val()+'"}');
        }
    }

    function changeLanguage(lang){
        if(location.href.indexOf("lang")==-1){
            location.href += "&lang="+lang;
        }else{
            replaceParamVal("lang",lang);
        }
    }

    //替换指定传入参数的值,paramName为参数,replaceWith为新值
    function replaceParamVal(paramName,replaceWith) {
        var oUrl = this.location.href.toString();
        var re=eval('/('+ paramName+'=)([^&]*)/gi');
        var nUrl = oUrl.replace(re,paramName+'='+replaceWith);
        this.location = nUrl;
        window.location.href=nUrl
    }
</script>
</body>
</html>